﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Control.Bus;

namespace QuanLyKho
{
    public partial class FrmExport : Form
    {
        List<BusExportBillDetail> BillDetails = new List<BusExportBillDetail>();
        List<BusExportBillDetail> BillDetailstoDelete = new List<BusExportBillDetail>();
        BusExportBillDetail BillDetailtoUpdate = null;
        bool saved = true;
        BusStaff staff = new BusStaff()
        {
            ID = 1,
            UserName = "admin",
            PassWord = "admin"
        };
        BusExportBill Bill = new BusExportBill();
        public FrmExport()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            //dataGridView1.DataSource = BillDetails;
            Bill = BusExportBill.FindByDateAndStaff(DateTime.Now, staff);
            if (Bill.ID == -1)
            {
                Bill.Staff = staff;
                Bill.Date = DateTime.Now;
                Bill.Insert();
            }

        }
      
        public FrmExport(BusExportBill _Bill, BusStaff _Staff)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            Bill = _Bill;
            staff = _Staff;
            if (Bill.ID == -1)
                Bill.Insert();
            BillDetails = Bill.GetBillDetail();
            if (BillDetails.Count != 0)
                bindingDataSource();
            if (Bill.BillName == "Thường") 
            {
                txtMaBO.Enabled = false;
                txtTenBO.Enabled = false;

            }
            else
            {
                txtMaBO.Text = Bill.BillCode;
                txtTenBO.Text = Bill.BillName;
                txtMaBO.Enabled = true;
                txtTenBO.Enabled = true;
            }

        }
        private void btchonSp_Click(object sender, EventArgs e)
        {
            string ProdCode = null;
            FrmChooseProd frm = new FrmChooseProd();
            frm.ShowDialog();
            ProdCode = frm.Resuilt;
            txtMa.Text = ProdCode;
        }

        private void txtMa_TextChanged(object sender, EventArgs e)
        {
            string MaProd = txtMa.Text;
            BusProduct Prod = BusProduct.GetProdByCode(MaProd);
            try
            {
                lbTenValue.Text = Prod.ProductName;
                lbTonValue.Text = Prod.GetTonKho().ToString();
                lbKeValue.Text = Prod.ShelfName;
            }
            catch
            {
                lbTenValue.Text = "no value";
                lbKeValue.Text = "no value";
                lbTonValue.Text = "no value";
            }
        }

        private void btHuy_Click(object sender, EventArgs e)
        {
            clear();
        }
        private void clear()
        {
            txtMa.Text = null;
            txtSoLuong.Text = null;
            txtThucPhat.Text = null;
            txtNhanLai.Text = null;
            lbKeValue.Text = "no value";
            lbTonValue.Text = "no value";
            lbTenValue.Text = "no value";
            BillDetailtoUpdate = null;


        }

        private void FrmExport_Load(object sender, EventArgs e)
        {
            
        }

        private void btNhap_Click(object sender, EventArgs e)
        {
            nhapdatagrid();
            clear();
            IsNotSave();
        }

        private void IsNotSave()
        {
            saved = false;
            groupBox3.Text = "Danh sách nhập (*)";
        }

        private void nhapdatagrid()
        {
            string MaProd = txtMa.Text;
            BusProduct Prod = new BusProduct();
            Prod.ProductCode=MaProd;
            Prod.GetProperty();
            int quantity = 0;
            try { quantity= Convert.ToInt32(txtSoLuong.Text);}
            catch{}
            int realquantity = 0;
            try { realquantity = Convert.ToInt32(txtThucPhat.Text); }
            catch { }
            int recieve = 0;
            try { recieve = Convert.ToInt32(txtNhanLai.Text); }
            catch { }
            BusExportBillDetail billdetail = new BusExportBillDetail()
            {
                ID = -1,
                Bill = Bill,
                Prod = Prod,
                Quantity = quantity,
                RealQuantity=realquantity,
                Recieve=recieve
            };
            BillDetails.Add(billdetail);
            if (BillDetailtoUpdate != null)
            {
                BillDetails.Remove(BillDetailtoUpdate);
                BillDetailstoDelete.Add(BillDetailtoUpdate);

            }
            bindingDataSource();

            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                row.Selected = false;
            }
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
        }

        private void bindingDataSource()
        {
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = BillDetails;
        }

        private void btPaste_Click(object sender, EventArgs e)
        {
            string s = Clipboard.GetText();
            string[] lines = s.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            //ITERATION HEADER-CHECK


            foreach (string line in lines)
            {
                string[] cells = line.Split('\t');
                BusProduct p = new BusProduct();
                p.ProductCode = cells[0];
                p.GetProperty();
                int celllast = 0;
                if (cells.Count() != 1)
                {

                    try { celllast = int.Parse(cells.Last()); }
                    catch { }
                }


                BusExportBillDetail bd = new BusExportBillDetail()
                {
                    Bill = Bill,
                    Prod = p,
                    ID = -1,
                    Quantity = celllast,

                };
                BillDetails.Add(bd);

            }
            bindingDataSource();
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                row.Selected = false;
            }
            for (int i = dataGridView1.Rows.Count - lines.Count(); i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Selected = true;
            }
            IsNotSave();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.V)
            {
                string s = Clipboard.GetText();
                string[] lines = s.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                //ITERATION HEADER-CHECK


                foreach (string line in lines)
                {
                    string[] cells = line.Split('\t');
                    BusProduct p = new BusProduct();
                    p.ProductCode = cells[0];
                    p.GetProperty();
                    int celllast = 0;
                    if (cells.Count() != 1)
                    {

                        try { celllast = int.Parse(cells.Last()); }
                        catch { }
                    }


                    BusExportBillDetail bd = new BusExportBillDetail()
                    {
                        Bill = Bill,
                        Prod = p,
                        ID = -1,
                        Quantity = celllast,

                    };
                    BillDetails.Add(bd);

                }
                bindingDataSource();
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    row.Selected = false;
                }
                for (int i = dataGridView1.Rows.Count - lines.Count(); i < dataGridView1.Rows.Count; i++)
                {
                    dataGridView1.Rows[i].Selected = true;
                }
                IsNotSave();
            }
        }

        private void btSua_Click(object sender, EventArgs e)
        {
            BusExportBillDetail billdetail = BillDetails[dataGridView1.SelectedRows[0].Index];
            txtMa.Text = billdetail.MaProd;
            txtSoLuong.Text = billdetail.Quantity.ToString();
            txtThucPhat.Text = billdetail.RealQuantity.ToString();
            txtNhanLai.Text = billdetail.Recieve.ToString();
            BillDetailtoUpdate = billdetail;
        }

        private void btXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("bạn có muốn xóa không ?", "Xac Dinh", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                List<BusExportBillDetail> delete = new List<BusExportBillDetail>();
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    delete.Add(BillDetails[row.Index]);
                }
                foreach (BusExportBillDetail item in delete)
                {
                    BillDetails.Remove(item);
                    if (item.ID > 0)
                    {
                        BusExportBillDetail Busremove = BusExportBillDetail.GetByID(item.ID);
                        BillDetailstoDelete.Add(Busremove);

                    }
                    else
                        BillDetailstoDelete.Add(item);
                }
                bindingDataSource();
                IsNotSave();
            }
        }

        private void btLuu_Click(object sender, EventArgs e)
        {
            Luu();
        }

        private void Luu()
        {
            if (txtMaBO.Text == "" && txtMaBO.Enabled == true)
                label3.Text = "X";
            else
            {
                if (Bill.BillName != "Thường")
                {
                    Bill.BillName = txtTenBO.Text;
                    Bill.BillCode = txtMaBO.Text;
                    Bill.UpDate();
                }
                int i = 0;
                foreach (BusExportBillDetail item in BillDetails)
                {
                    if (item.ID == -1 && item.Prod.ID != 0)
                        try
                        {

                            item.Insert();
                            item.IsSaved = true;
                        }
                        catch (Exception ex) { MessageBox.Show(ex.ToString()); }
                    else
                    {
                        item.Update();
                        item.IsSaved = true;
                    }
                    i++;
                }
                foreach (BusExportBillDetail item in BillDetailstoDelete)
                {
                    try
                    {
                        item.Delete();
                    }
                    catch
                    {

                    }
                }
                BillDetailstoDelete = new List<BusExportBillDetail>();

                IsSaved();
                label3.Text = null;
            }
        }

        private void IsSaved()
        {
            saved = true;
            groupBox3.Text = "Danh sách nhập";
        }

        private void btThoat_Click(object sender, EventArgs e)
        {
            if (saved == true)
            {
                this.Close();
            }
            else
            {
                DialogResult dialogresuilt = MessageBox.Show("Một só dữ liệu chưa được lưu. Bạn có muôn lưu không ?", "Xac Dinh", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dialogresuilt == DialogResult.Yes)
                {
                    Luu();
                    this.Close();
                }
                else if (dialogresuilt == DialogResult.No)
                    this.Close();

            }
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex!=-1)
            {
                IsNotSave();
                BillDetails[e.RowIndex].IsSaved = false;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            BusExportBillDetail billdetail = new BusExportBillDetail();
            foreach (BusExportBillDetail item in BillDetails)
            {
                if (item.MaProd == textBox1.Text)
                    billdetail = item;
            }
            if (billdetail.ID == 0)
                label5.Text = "Không tìm thấy!!!";
            else
            {
                label5.Text = "";
                txtNhanLai.Text = billdetail.Recieve.ToString();
            }
        }

        private void btNhanLai_Click(object sender, EventArgs e)
        {
            foreach (BusExportBillDetail item in BillDetails)
            {
                if (item.MaProd == textBox1.Text)
                    item.Recieve=Convert.ToInt32(txtNhanLai.Text);
            }
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.Selected = false;
                if (row.Cells[1].Value.ToString() == textBox1.Text)
                {
                    row.Selected = true;
                    row.Cells[6].Value = false;
                }
            }
            IsNotSave();
        }


    }
}
